//
//  ESTActivityAchieveTableViewCell.m
//  ESTSCRMAPP
//
//  Created by 李贤立 on 2018/10/15.
//  Copyright © 2018年 Capfer. All rights reserved.
//

#import "ESTActivityCustomerInfoTableViewCell.h"
#import "ESTHorizontalValueView.h"
#import "ESTCustomerInfoModel.h"
#import "UILabel+Space.h"
#import "TYZCallPhoneTool.h"

#define DifferentCellTypeValue               100
#define SearchResultCellTypeValue            10000

@interface ESTActivityCustomerInfoTableViewCell ()
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *phoneLabel;
@property (weak, nonatomic) IBOutlet UIImageView *sexImageView;
@property (weak, nonatomic) IBOutlet UIButton *phoneButton;
@property (weak, nonatomic) IBOutlet UIView *mainView;
@property (weak, nonatomic) IBOutlet UILabel *followUpLabel;
/**
 *  cell类型
 *  如果小于DifferentCellTypeValue则是我的业绩的Cell
 *  如果大于等于DifferentCellTypeValue则是跟进信息的Cell
 */
@property(nonatomic, assign) NSInteger item;
@end
// mainView之外的70的固定高度:CustomerInfoTableViewCell_FirstPartHeight
@implementation ESTActivityCustomerInfoTableViewCell

/**
 业绩的客户信息Cell

 @param tableView tableView
 @param item 业绩类型
 @return 创建Cell
 */
+ (instancetype)creatActivityAchieveTableViewCell:(UITableView *)tableView item:(NSInteger)item {
    ESTActivityCustomerInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ESTActivityCustomerInfoTableViewCell"];
    if (cell == nil) {
        cell = [[NSBundle mainBundle] loadNibNamed:@"ESTActivityCustomerInfoTableViewCell" owner:nil options:nil].lastObject;
    }
    cell.item = item;
    return cell;
}

/**
 跟进的客户信息

 @param tableView tableView
 @param item 跟进类型
 @return 创建Cell
 */
+ (instancetype)creatActivityCustomerInfoTableViewCell:(UITableView *)tableView item:(NSInteger)item {
    ESTActivityCustomerInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ESTActivityCustomerInfoTableViewCell"];
    if (cell == nil) {
        cell = [[NSBundle mainBundle] loadNibNamed:@"ESTActivityCustomerInfoTableViewCell" owner:nil options:nil].lastObject;
    }
    cell.item = item + DifferentCellTypeValue;
    return cell;
}

/**
 搜索结果
 
 @param tableView tableView
 @return 创建Cell
 */
+ (instancetype)creatActivitySearchResultTableViewCell:(UITableView *)tableView {
    ESTActivityCustomerInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ESTActivityCustomerInfoTableViewCell"];
    if (cell == nil) {
        cell = [[NSBundle mainBundle] loadNibNamed:@"ESTActivityCustomerInfoTableViewCell" owner:nil options:nil].lastObject;
    }
    cell.item = SearchResultCellTypeValue;
    return cell;
}
- (void)setModel:(ESTCustomerInfoModel *)model {
    _model = model;
    self.nameLabel.text = model.CUST_NAME;
    self.phoneLabel.text = model.CUST_PHONE;
    NSString *sexImageName = @"";
    if ([model.CUST_SEX isEqualToString:[@"男" S]]) {
        sexImageName = @"client_male_list_icon";
    } else if ([model.CUST_SEX isEqualToString:[@"女" S]]) {
        sexImageName = @"client_female_list_icon";
    }
    self.sexImageView.image = [UIImage imageNamed:sexImageName];
    self.followUpLabel.text = [NSString stringWithFormat:@"%@%ld%@", [@"跟进了" S], (long)[model.LINK_COUNT integerValue], [@"次" S]];
    [self setupMainView];
}
- (IBAction)didClickPhoneButton:(UIButton *)sender {
    [CallPhoneTool callPhoneWithNumber:@"10010" inActivity_id:self.model.VE_ACTIVITY_ID custom_id:self.model.VE_ACTIVITY_CUST_ID];
    WEAKSELF
    // 真实通话时间
    [CallPhoneTool setCallPhoneRealTime:^(NSInteger timeSecond) {
//        [TYZSystemDialog dialogWithTitle:[NSString stringWithFormat:@"%@：%ld''", [@"打完电话，是否立即跟进？\n本次通话时长" S], (long)timeSecond] dialogType:SystemDialogType_Destructive_Right complement:^{
//            if (weakSelf.complementDialBlock) {
//                weakSelf.complementDialBlock([NSString stringWithFormat:@"%ld", (long)timeSecond]);
//            }
//        }];
    }];
    // 只是拨出时间
    [CallPhoneTool setCallPhoneDialTime:^(NSInteger timeSecond) {
        [TYZSystemDialog dialogWithTitle:[NSString stringWithFormat:@"%@：%ld''", [@"打完电话，是否立即跟进？\n本次通话时长" S], (long)timeSecond] dialogType:SystemDialogType_Destructive_Right complement:^{
            if (weakSelf.complementDialBlock) {
                weakSelf.complementDialBlock([NSString stringWithFormat:@"%ld", (long)timeSecond]);
            }
        }];
    }];
}
- (NSString *)spellSourceName {
    NSString *value = @"";
    if (self.model.SOURCE_BIG_CODE.length > 0) {
        value = self.model.SOURCE_BIG_CODE;
        if (self.model.SOURCE_SMALL_CODE.length > 0) {
            value = [value stringByAppendingString:[NSString stringWithFormat:@"-%@", self.model.SOURCE_SMALL_CODE]];
        }
    } else {
        if (self.model.SOURCE_SMALL_CODE.length > 0) {
            value = self.model.SOURCE_SMALL_CODE;
        }
    }
    return value;
}
- (void)setupMainView {
    if (self.item == SearchResultCellTypeValue) {
        [self setupSearchResultCell];
        return;
    }
    if (self.item < DifferentCellTypeValue) {
        [self setupAchieveInfoCell];
        return;
    }
    [self setupFollowUpInfoCell];
}
- (CGFloat)addHorizonralValueViewWithTitle:(NSString *)title value:(NSString *)value topMargin:(CGFloat)topMargin clickValue:(void(^)(void))clickValue {
    CGFloat height = topMargin;
    ESTHorizontalValueView *childView = [ESTHorizontalValueView creatHorizontalValueViewWithName:title value:value clickValue:^{
        if (clickValue) {
            clickValue();
        }
    }];
    [self.mainView addSubview:childView];
    [childView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.mainView);
        make.top.equalTo(self.mainView).offset(height);
        make.height.mas_equalTo(ActivityAchieveTableViewCell_ContentLineHeight);
    }];
    height += ActivityAchieveTableViewCell_ContentLineHeight;
    return height;
}
- (void)setupSearchResultCell {
    // 距离顶部的高度
    CGFloat topMargin = ActivityAchieveTableViewCell_LinePadding * 0.5;
    // 归属活动
    WEAKSELF
    topMargin = [self addHorizonralValueViewWithTitle:[@"归属活动:" S] value:self.model.VE_ACTIVITY_CN topMargin:topMargin clickValue:^{
        if (weakSelf.didClickActivityNameBlock) {
            weakSelf.didClickActivityNameBlock(weakSelf.model.VE_ACTIVITY_ID);
        }
    }];
    // 客户来源
    topMargin = [self addHorizonralValueViewWithTitle:[@"客户来源:" S] value:[self spellSourceName] topMargin:topMargin clickValue:nil];
    // 意向车型
    [self addHorizonralValueViewWithTitle:[@"意向车型:" S] value:self.model.INTENT_CARTYPE_CN topMargin:topMargin clickValue:nil];
}
- (void)setupAchieveInfoCell {
    // 距离顶部的高度
    CGFloat topMargin = ActivityAchieveTableViewCell_LinePadding * 0.5;
    // 归属活动
    WEAKSELF
    topMargin = [self addHorizonralValueViewWithTitle:[@"归属活动:" S] value:self.model.VE_ACTIVITY_CN topMargin:topMargin clickValue:^{
        if (weakSelf.didClickActivityNameBlock) {
            weakSelf.didClickActivityNameBlock(weakSelf.model.VE_ACTIVITY_ID);
        }
    }];
    // 客户来源
    topMargin = [self addHorizonralValueViewWithTitle:[@"客户来源:" S] value:[self spellSourceName] topMargin:topMargin clickValue:nil];
    if (self.item == 2) {
        // 未成功沟通
        topMargin = [self addHorizonralValueViewWithTitle:[@"意向车型:" S] value:self.model.INTENT_CARTYPE_CN topMargin:topMargin clickValue:nil];
    }
    
    TYZView *remarkView = [[TYZView alloc] init];
    [self.mainView addSubview:remarkView];
    [remarkView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mainView).offset(topMargin);
        make.left.equalTo(self.mainView).offset(20);
        make.right.equalTo(self.mainView).offset(-20);
        make.bottom.equalTo(self.mainView).offset(-ActivityAchieveTableViewCell_LinePadding * 0.5);
    }];
    remarkView.backgroundColor = ESTBackgroundColor;
    remarkView.layer.cornerRadius = 5.0;
    NSString *text = [self.model.POSITION1 stringByReplacingOccurrencesOfString:@"\\r\\n" withString:@"\n"];
    if ([text hasSuffix:@"\n"]) {
        text = [text substringToIndex:text.length - 1];
    }
    TYZLabel *label = [TYZLabel labelWithText:text];
    label.font = [UIFont systemFontOfSize:CoreInfo.fontSize - 2];
    label.numberOfLines = 0;
    [label changeLineSpaceSpace:5];
    label.textColor = TYZLightMColor;
    [remarkView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(remarkView).offset(ActivityAchieveTableViewCell_LinePadding * 0.5);
        make.left.equalTo(remarkView).offset(ActivityAchieveTableViewCell_LinePadding);
        make.right.equalTo(remarkView);
        make.bottom.equalTo(remarkView).offset(-ActivityAchieveTableViewCell_LinePadding * 0.5);
    }];
}
- (void)setupFollowUpInfoCell {
    // 距离顶部的高度
    CGFloat topMargin = ActivityAchieveTableViewCell_LinePadding * 0.5;
    WEAKSELF
    if (self.item == DifferentCellTypeValue) {
        // 归属活动
        topMargin = [self addHorizonralValueViewWithTitle:[@"归属活动:" S] value:self.model.VE_ACTIVITY_CN topMargin:topMargin clickValue:^{
            if (weakSelf.didClickActivityNameBlock) {
                weakSelf.didClickActivityNameBlock(weakSelf.model.VE_ACTIVITY_ID);
            }
        }];
        // 客户来源
        topMargin = [self addHorizonralValueViewWithTitle:[@"客户来源:" S] value:[self spellSourceName] topMargin:topMargin clickValue:nil];
        // 意向车型
        topMargin = [self addHorizonralValueViewWithTitle:[@"意向车型:" S] value:self.model.INTENT_CARTYPE_CN topMargin:topMargin clickValue:nil];
        // 下发时间
        [self addHorizonralValueViewWithTitle:[@"下发时间:" S] value:[self.model.RECEIVE_TIME getLocalDateFormate] topMargin:topMargin clickValue:nil];
    } else {
        // 设置标签栏
        NSArray *arr = [self.model.FOLLOWUP_LABLE componentsSeparatedByString:@","];
        if (arr.count > 1) {
            topMargin = [self setupLabelsView:arr topMargin:topMargin];
        }
        // 归属活动
        topMargin = [self addHorizonralValueViewWithTitle:[@"归属活动:" S] value:self.model.VE_ACTIVITY_CN topMargin:topMargin clickValue:^{
            if (weakSelf.didClickActivityNameBlock) {
                weakSelf.didClickActivityNameBlock(weakSelf.model.VE_ACTIVITY_ID);
            }
        }];
        // 意向车型
        topMargin = [self addHorizonralValueViewWithTitle:[@"意向车型:" S] value:self.model.INTENT_CARTYPE_CN topMargin:topMargin clickValue:nil];
        if (self.item == DifferentCellTypeValue + 1) {
            // 最近跟进
            topMargin = [self addHorizonralValueViewWithTitle:[@"最近跟进:" S] value:[self.model.LAST_FOLLOWUP_TIME getLocalDateFormate] topMargin:topMargin clickValue:nil];
            // 下次跟进
            [self addHorizonralValueViewWithTitle:[@"下次跟进:" S] value:[self.model.PLAN_FOLLOWUP_TIME getLocalDateFormate] topMargin:topMargin clickValue:nil];
        } else {
            // 下次跟进
            topMargin = [self addHorizonralValueViewWithTitle:[@"计划到场时间:" S] value:[self.model.PLAN_COME_TIME getLocalDateFormate] topMargin:topMargin clickValue:nil];
            // 确认到场
            [self setupPlamComingButtonWithTopMargin:topMargin];
        }
    }
}
- (CGFloat)setupLabelsView:(NSArray<NSString *> *)labelArray topMargin:(CGFloat)topMargin {
    NSInteger lines = labelArray.count / 4 + 1;
    if (labelArray.count % 4 == 0) {
        lines--;
    }
    CGFloat height = topMargin;
    height += ActivityAchieveTableViewCell_LabelBorderHeight * lines;
    TYZView *labelView = [[TYZView alloc] init];
    [self.mainView addSubview:labelView];
    [labelView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mainView);
        make.left.equalTo(self.mainView).offset(20);
        make.right.equalTo(self.mainView).offset(-20);
        make.height.mas_equalTo(height);
    }];
    UIFont *font = TYZFont(CoreInfo.fontSize * 0.8);
    for (NSInteger i = 0; i < lines; i++) {
        CGFloat leftMargin = 0;
        for (NSInteger j = 0; j < 4; j++) {
            if (i * 4 + j >= labelArray.count) {
                break;
            }
            NSString *title = labelArray[i * 4 + j];
            TYZLabel *label = [TYZLabel labelWithText:title];
            CGSize size = [title getSizeWithFont:font];
            [labelView addSubview:label];
            [label mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(labelView).offset(ActivityAchieveTableViewCell_LinePadding * 0.5 + ActivityAchieveTableViewCell_LabelBorderHeight * i);
                make.left.equalTo(labelView).offset(leftMargin);
                make.width.mas_equalTo(size.width + 10);
                make.height.mas_equalTo(size.height + 10);
            }];
            label.textColor = TYZLightMColor;
            label.layer.borderColor = TYZLightColor.CGColor;
            label.layer.borderWidth = 1.0;
            label.font = font;
            label.textAlignment = NSTextAlignmentCenter;
            leftMargin += size.width + 10 + 10;
        }
    }
    return height;
}
- (void)setupPlamComingButtonWithTopMargin:(CGFloat)topMargin {
    TYZButton *button = [[TYZButton alloc] init];
    [self.mainView addSubview:button];
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mainView).offset(20);
        make.right.equalTo(self.mainView).offset(-20);
        make.top.equalTo(self.mainView).offset(topMargin + ActivityAchieveTableViewCell_LinePadding * 0.5);
        make.height.mas_equalTo(ActivityAchieveTableViewCell_LabelBorderHeight);
    }];
    BOOL isComed = [self.model.IS_COME integerValue];
    NSString *title = isComed ? [@"已到场" S] : [@"确认到场" S];
    UIColor *bgColor = isComed ? TYZLightMMColor : ThemeColor;
    UIColor *textColor = isComed ? TYZBlackColor : TYZWhiteColor;
    [button setTitleColor:textColor forState:UIControlStateNormal];
    [button setBackgroundColor:bgColor];
    [button setTitle:title forState:UIControlStateNormal];
    button.titleLabel.font = TYZFont(CoreInfo.fontSize);
    [button addTarget:self action:@selector(didClickComedButton:) forControlEvents:UIControlEventTouchUpInside];
}
- (void)didClickComedButton:(TYZButton *)button {
    if ([self.model.IS_COME integerValue]) {
        [TYZLoadingView showNormal:[@"已到场" S]];
    } else {
        self.model.IS_COME = @"1";
        __weak typeof(button) weakButton = button;
        [TYZLoadingView showMessage:nil];
        [ESTCustomerInfoModel preserveCustomerInfoWithModel:self.model duration:nil guid:[TYZTool GUID] complement:^(NSString *message) {
            [TYZLoadingView hideHUD];
            BOOL isComed = [message isEqualToString:Request_Success];
            if (isComed == NO) return;
            [weakButton setTitleColor:TYZBlackColor forState:UIControlStateNormal];
            [weakButton setBackgroundColor:TYZLightMMColor];
            [weakButton setTitle:[@"已到场" S] forState:UIControlStateNormal];
        }];
    }
}
@end
